<template>
    <p style="line-height: 3.125rem; font-size: 1rem; font-weight: bold" class="main_text">
        积分发放
    </p>
    <div class="main">
        <!-- #################################### 查询 #################################### -->
        <div class="main_nav p20">
            <el-form :model="pointsInquiry" class="df aic">
                <el-form-item label="规则名称：" class="mr20" style="width: 20%">
                    <el-input v-model.trim="pointsInquiry.keyword" placeholder="规则名称：" />
                </el-form-item>
                <el-form-item label="积分类型：" class="mr20" style="width: 20%">
                    <el-input v-model="pointsInquiry.typeName" placeholder="积分类型：" />
                </el-form-item>
                <el-form-item label="是否启用：" class="mr20" style="width: 20%">
                    <el-select v-model="pointsInquiry.ifTakeEffect" placeholder="" size="large" style="width: 240px">
                        <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 20%">
                    <div class="df">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button type="primary" plain @click="handleReset">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <!-- #################################### 表单 #################################### -->
        <div class="content p20 mt20">
            <el-button type="primary" @click="openDrawer">新建发放规则</el-button>
            <el-button type="danger" plain @click="batchDelete">
                批量删除</el-button>
            <el-table @selection-change="handleSelectionChange" :data="tableList" style="width: 100%" class="mt20"
                :header-cell-style="{ background: '#f0f6fe' }" max-height="450">
                <el-table-column type="selection" />
                <el-table-column label="编号" prop="id" />
                <el-table-column label="任务/活动名称" prop="name" />
                <el-table-column label="积分类型" prop="typeId">
                    <template #default="props">
                        {{
                            props.row.typeId === 0
                                ? '消费积分'
                                : props.row.typeId === 1
                                    ? '行为积分'
                                    : '活动积分'
                        }}
                    </template>
                </el-table-column>
                <el-table-column label="发放数量" prop="everydaySignReward" />
                <el-table-column label="积分有效期" prop="effectEndAt">
                    <template #default="props">
                        {{ props.row.effectStartAt }} 至 {{ props.row.effectEndAt }}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="updatedAt" />
                <el-table-column label="是否启用" prop="ifTakeEffect">
                    <template #default="props">
                        <el-switch v-model="props.row.ifTakeEffect" disabled />
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="props">
                        <el-button size="small" link type="primary" @click="edit(props.row)">编辑</el-button>
                        <el-button size="small" link type="danger" @click="deleteData(props.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- #################################### 分页 #################################### -->
            <el-pagination @current-change="handleCurrentChange" v-model:current-page="currentPage" small background
                layout="prev, pager, next" :total="total" class="mt20" />

            <!-- #################################### 添加侧边抽屉 #################################### -->
            <el-drawer v-model="isShowDrawer" title="新建发放规则" :with-header="false" size="30%">
                <p class="drawerText">新建发放规则</p>
                <el-form :model="addRuleFrom" label-width="auto" style="" :label-position="'top'">
                    <el-form-item>
                        <el-input disabled placeholder="基础信息"></el-input>
                    </el-form-item>
                    <el-form-item label="积分类型">
                        <el-select v-model="addRuleFrom.typeId" size="large">
                            <el-option v-for="item in ruleOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="规则名称">
                        <el-input v-model="addRuleFrom.name" placeholder="">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input disabled placeholder="规则设置"></el-input>
                    </el-form-item>
                    <!-- 消费积分表单 -->
                    <template v-if="addRuleFrom.typeId < 1">
                        <el-form-item label="发放条件">
                            <el-col :span="2"> 每消费 </el-col>
                            <el-col :span="10">
                                <el-input v-model="consumeNumber" placeholder="输入">
                                    <template #suffix> 元 </template>
                                </el-input>
                            </el-col>
                            <el-col :span="2" class="text-tac">
                                <span class="text-gray-500">获得</span>
                            </el-col>
                            <el-col :span="10">
                                <el-input v-model="getNumber">
                                    <template #suffix> 积分 </template>
                                </el-input>
                            </el-col>
                        </el-form-item>
                    </template>

                    <!-- 行为积分 && 浏览页面得积分 -->
                    <!-- <template v-if="
                        addRuleFrom.typeId === 1
                    ">
                        <el-form-item label="发放条件">
                            <el-col :span="2"> 每天浏览商城 </el-col>
                            <el-col :span="10">
                                <el-input v-model="addRuleFrom.require" placeholder="输入">
                                    <template #suffix> 秒 </template>
                                </el-input>
                            </el-col>
                            <el-col :span="2" class="text-tac">
                                <span class="text-gray-500">获得</span>
                            </el-col>
                            <el-col :span="10">
                                <el-input v-model="addRuleFrom.get">
                                    <template #suffix> 积分 </template>
                                </el-input>
                            </el-col>
                        </el-form-item>
                    </template> -->
                    <!-- 行为积分 && 签到得积分 -->
                    <template v-if="
                        addRuleFrom.typeId === 1
                    ">
                        <el-form-item label="发放条件">
                            <el-col :span="5"> 每天签到可获得 </el-col>
                            <el-col :span="13">
                                <el-input v-model.number="addRuleFrom.everydaySignReward" placeholder="输入">
                                    <template #suffix> 积分 </template>
                                </el-input>
                            </el-col>
                            <el-col :span="6"> 只能签到一次。 </el-col>
                        </el-form-item>
                        <!-- 连签奖励 -->
                        <el-form-item label="连签奖励">
                            <el-radio-group v-model="signInNumber" class="df fdc w100" @change="handlesignIn">
                                <el-radio :label="0">无连签奖励</el-radio>
                                <el-row class="aie">
                                    <el-col :span="6">
                                        <el-radio :label="1">连签奖励设置</el-radio>
                                    </el-col>
                                    <el-col :span="17">
                                        <el-icon :size="15">
                                            <el-tooltip class="box-item" effect="light" placement="bottom"
                                                content="连续签到可获得的额外积分，目前以连续签到7天为一周期，不再继续叠加。">
                                                <Warning />
                                            </el-tooltip>
                                        </el-icon>
                                    </el-col>
                                </el-row>
                            </el-radio-group>
                            <template v-for="(item, index) in addRuleFrom.continueSignReward" :key="index">
                                <el-row class="mt16">
                                    <el-col :span="11" class="df order">
                                        <el-text style="white-space: nowrap; padding-right: 3px">连续签到满</el-text>
                                        <el-select v-model="item.key" size="large" @change="handleSelectDay">
                                            <el-option v-for="item in dayOptions" :key="item.value" :label="item.label"
                                                :disabled="item.disabled" :value="item.value" />
                                            <template #prefix> 天 </template>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="11" class="df">
                                        <el-text style="white-space: nowrap; padding: 0 3px">可额外获得</el-text>
                                        <el-input v-model="item.value" placeholder="输入">
                                            <template #suffix> 积分 </template>
                                        </el-input>
                                    </el-col>
                                    <el-col :span="2" style="align-self: center">
                                        <el-icon style="margin: 0 5px" @click="handleDelete(index)">
                                            <RemoveFilled />
                                        </el-icon>
                                        <el-icon @click="handleAdd"
                                            v-if="index === addRuleFrom.continueSignReward.length - 1">
                                            <CirclePlusFilled />
                                        </el-icon>
                                    </el-col>
                                </el-row>
                            </template>
                        </el-form-item>
                    </template>
                    <!-- 活动积分 -->
                    <!-- <template v-if="addRuleFrom.typeId === 2">
                        <div v-for="(item, index) in activityArr" :key="index">
                            <el-row class="mb10">
                                <el-col :span="1">
                                    <el-icon>
                                        <List />
                                    </el-icon>
                                </el-col>
                                <el-col :span="21">
                                    <el-text>任务{{ index + 1 }}</el-text>
                                </el-col>
                                <el-col :span="2" class="df jcfe">
                                    <el-icon @click="handleDeleteActivity(index)">
                                        <Delete />
                                    </el-icon>
                                </el-col>
                            </el-row>
                            <el-form-item label="任务名称">
                                <el-select v-model="item.name" size="large">
                                    <el-option v-for="item in taskNameOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="奖励积分数量">
                                <el-input v-model="item.score">
                                    <template #suffix> 积分 </template>
                                </el-input>
                            </el-form-item>
                        </div>
                        <el-button @click="handleAddActivity">
                            <el-icon>
                                <Plus />
                            </el-icon>增加任务
                        </el-button>
                    </template> -->

                    <el-form-item label="积分有效期">
                        <el-radio-group v-model="effectTime" class="df fdc w100" @change="handleRadio">
                            <el-radio :label="0">永久有效</el-radio>
                            <el-row>
                                <el-col :span="4">
                                    <el-radio :label="1">固定天数</el-radio>
                                </el-col>
                                <el-col :span="20">
                                    <el-input v-model="effectDay" placeholder="领取后到期天数" :disabled="effectTime === 0">
                                        <template #suffix> 天 </template>
                                    </el-input>
                                </el-col>
                            </el-row>
                            <el-row v-if="addRuleFrom.type === '活动积分'">
                                <el-col :span="4">
                                    <el-radio :label="2">日期范围</el-radio>
                                </el-col>
                                <el-col :span="20">
                                    <el-date-picker v-model="value1" type="daterange" range-separator="To"
                                        start-placeholder="开始时间" end-placeholder="结束时间" />
                                </el-col>
                            </el-row>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="规则说明">
                        <el-col :span="24">
                            <el-input v-model="addRuleFrom.description" maxlength="300" placeholder="规则说明"
                                show-word-limit type="textarea" /></el-col>
                    </el-form-item>
                    <el-form-item>
                        是否启用
                        <el-switch v-model="addRuleFrom.ifTakeEffect" />
                    </el-form-item>
                    <el-form-item class="jcfe">
                        <el-button class="drawer-btn" @click="isShowDrawer = false">取消</el-button>
                        <el-button class="drawer-btn" type="primary" @click="handleSubmit">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import { RequestPointPrivideList, RequestPointDeleteList, RequestPointAddSave, RequestPointSingleData } from '@/api/path/index.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    Warning,
    RemoveFilled,
    CirclePlusFilled,
    Delete,
    List,
    Plus,
} from '@element-plus/icons-vue';
import {
    ref,
    onMounted,
    watch,
    computed,
} from 'vue';
import { formatDate, calculateExpiryTime, daysUntil } from '@/utils/index'

onMounted(() => {
    // initSearch();
});
/*积分查询参数*/
const pointsInquiry = ref({
    keyword: '',
    page: 1,
    rows: 10,
    ifTakeEffect: '',
    typeName: '',
});

//积分查询列表
const options = [
    {
        value: true,
        label: '已启用',
    },
    {
        value: false,
        label: '未启用',
    },
];
const tableList = ref();
const total = ref<number>();
const initSearch = async () => {
    let {
        resultObj: { list, count },
    } = await RequestPointPrivideList(pointsInquiry.value);
    tableList.value = list;
    total.value = count;
};

//查询按钮
const handleSearch = () => {
    // initSearch();
};
//重置搜索框
const handleReset = () => {
    Object.assign(
        pointsInquiry,
        (pointsInquiry.value = {
            page: 1,
            rows: 10,
            ifTakeEffect: '',
            keyword: '',
            typeName: '',
        }),
    );
    handleSearch();
};

//抽屉数据
const isShowDrawer = ref<boolean>(false);
const ruleOptions = [
    {
        value: 0,
        label: '消费积分',
    },
    {
        value: 1,
        label: '行为积分',
    },
    {
        value: 2,
        label: '活动积分',
    },
];
const dayOptions: { value: number; label: string; disabled?: boolean }[] = [
    { value: 1, label: '1' },
    { value: 2, label: '2' },
    { value: 3, label: '3' },
    { value: 4, label: '4' },
    { value: 5, label: '5' },
    { value: 6, label: '6' },
    { value: 7, label: '7' },
];
const openDrawer = () => {
    isShowDrawer.value = true;
    getNumber.value = '';
    consumeNumber.value = '';
    effectTime.value = '';
    effectDay.value = ''
    // addRuleFrom.value.name = '';
    // addRuleFrom.value.description = '';
    // addRuleFrom.value.id = '';
    addRuleFrom.value = {
        id: '',
        //积分类型
        typeId: 0,
        //规则名称
        name: '',
        //消费金额与所获积分
        payIntegralProportion: 0,
        //开始生效时间
        effectStartAt: '',
        //结束生效时间
        effectEndAt: '',
        //规则说明
        description: '',
        //是否启用
        ifTakeEffect: false,
        //行为积分 发放条件
        everydaySignReward: '',
        //连签奖励
        continueSignReward: [],

    }
};
interface AddRuleFrom {
    id: number | string,
    //积分类型
    typeId: number,
    //规则名称
    name: string,
    //消费金额与所获积分
    payIntegralProportion: number
    //开始生效时间
    effectStartAt: string
    //结束生效时间
    effectEndAt: string
    //规则说明
    description: string
    //是否启用
    ifTakeEffect: boolean
    //行为积分 发放条件
    everydaySignReward: string | number
    //连签奖励
    continueSignReward: { key: string | number, value: string | number }[]

    //活动数据
    // activityIntegral: [],
}
//新建规则
const addRuleFrom = ref<AddRuleFrom>({
    id: '',
    //积分类型
    typeId: 0,
    //规则名称
    name: '',
    //消费金额与所获积分
    payIntegralProportion: 0,
    //开始生效时间
    effectStartAt: '',
    //结束生效时间
    effectEndAt: '',
    //规则说明
    description: '',
    //是否启用
    ifTakeEffect: false,
    //行为积分 发放条件
    everydaySignReward: '',
    //连签奖励
    continueSignReward: [],

    //活动数据
    // activityIntegral: [],
});
//发放条件数据
//消费金额
const consumeNumber = ref<number | string>()
//获得金额
const getNumber = ref<number | string>()

//生效时间
const effectTime = ref<number | string>();
const effectDay = ref<number | string>()
const handleRadio = (value: any) => {
    addRuleFrom.value.effectStartAt = formatDate(new Date())
    if (value === 0) {
        addRuleFrom.value.effectEndAt = '';
        effectDay.value = ''
    }
};
watch(effectDay, (newVal) => {
    if (newVal) {
        addRuleFrom.value.effectEndAt = formatDate(calculateExpiryTime(formatDate(new Date()), Number(newVal)))
    } else {
        addRuleFrom.value.effectEndAt = ''
    }
})

//连续签到奖励

const handleAdd = () => {
    addRuleFrom.value.continueSignReward.push({ key: '', value: '' });
};
const handleDelete = (index: number) => {
    if (addRuleFrom.value.continueSignReward.length <= 1) {
        ElMessage.warning('至少需要一个签到奖励');
        return;
    }
    addRuleFrom.value.continueSignReward.splice(index, 1);
};
const signInNumber = ref<number>()
const handlesignIn = (value: any) => {
    //不是无连签奖励
    if (value !== 0) {
        addRuleFrom.value.continueSignReward.push({ key: '', value: '' })
    } else {
        //是无连签奖励
        addRuleFrom.value.continueSignReward = []
    }
};

const handleSelectDay = (value: any) => {
    console.log(value)
};
//不能比前一项的天数小
const dayComputed = computed(() => {
    // const lastItem = signInArr.value[signInArr.value.length - 1];
    // //为第二次选择添加disabled
    // dayOptions.forEach((option) => {
    //     if (option.value <= (lastItem.day as number)) {
    //         option.disabled = true;
    //     } else {
    //         option.disabled = false;
    //     }
    // });
});


//活动积分任务列表
const activityArr = ref<{ name: string | number; score: string | number }[]>([
    { name: '', score: '' },
]);

const handleDeleteActivity = (index: number) => {
    if (activityArr.value.length === 1) {
        return;
    }
    activityArr.value.splice(index, 1);
};
const handleAddActivity = () => {
    activityArr.value.push({
        name: '',
        score: '',
    });
};



//单个删除
const deleteData = async (id: number) => {
    let formData = new FormData()
    formData.append('ids', `${id}`)
    ElMessageBox.confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        RequestPointDeleteList(formData)
            .then(() => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                pointsInquiry.value.page = currentPage.value;
                initSearch()
            })
            .catch((err: { message: any; }) => {
                ElMessage({
                    type: 'error',
                    message: err.message,
                })
            })
    })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//批量删除
const listIds = ref<number[]>([]);
const batchDelete = () => {
    if (listIds.value.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
    }
    let formData = new FormData()
    formData.append('ids', `${listIds.value}`)
    ElMessageBox.confirm('确定删除数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        RequestPointDeleteList(formData)
            .then(() => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                pointsInquiry.value.page = currentPage.value;
                initSearch()
            }).catch((err: { message: any; }) => {
                ElMessage({
                    type: 'error',
                    message: err.message,
                })
            })
    })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
};
const handleSelectionChange = (val: object[]) => {
    listIds.value = []
    listIds.value = val.map((item) => item.id);
}
//编辑
const edit = (row: any) => {
    addRuleFrom.value.id = row.id
    RequestPointSingleData(row.id).then(({ resultObj }) => {
        let continueSignReward = JSON.parse(resultObj.continueSignReward.value)
        isShowDrawer.value = true;
        addRuleFrom.value.typeId = resultObj.typeId
        addRuleFrom.value.everydaySignReward = resultObj.everydaySignReward
        if (
            continueSignReward.length > 0
        ) {
            signInNumber.value = 1
            addRuleFrom.value.continueSignReward = continueSignReward

        } else {
            signInNumber.value = 0
        }
        //消费积分
        consumeNumber.value = resultObj.payIntegralProportion
        getNumber.value = resultObj.payIntegralProportion
        if (resultObj.effectEndAt === null) {
            effectTime.value = 0
            effectDay.value = ''
        } else {
            effectTime.value = 1
            effectDay.value = daysUntil(resultObj.effectEndAt)
        }
        addRuleFrom.value.description = resultObj.description
        addRuleFrom.value.name = resultObj.name
        addRuleFrom.value.ifTakeEffect = resultObj.ifTakeEffect

    }).catch((err: { message: string }) => {
        ElMessage({
            type: 'error',
            message: '获取当前数据失败'
        })
    })

}
/* ************************ 分页获取数据 ************************ */
const currentPage = ref(1);
const handleCurrentChange = (val: number) => {
    pointsInquiry.value.page = val;
    currentPage.value = val;
    initSearch()
};
/*新增规则提交*/
const handleSubmit = () => {

    if (addRuleFrom.value.typeId === 0) {
        addRuleFrom.value.payIntegralProportion = (getNumber.value as number) / (consumeNumber.value as number) * 1
    }

    RequestPointAddSave(addRuleFrom.value)
        .then((res: object) => {
            ElMessage({
                type: 'success',
                message: '添加成功',
            })
            isShowDrawer.value = false;
            initSearch()
        })
        .catch((err: { message: string; }) => {
            ElMessage({
                type: 'error',
                message: err.message,
            })
        })
}
</script>

<style scoped lang="scss">
.main {
    width: 100%;

    .main_nav {
        background-color: #fff;
    }

    .jcfe {
        ::v-deep(.el-form-item__content) {
            justify-content: flex-end;
        }
    }

    .drawer-btn {
        width: 90px;
        height: 40px;
        border-radius: 4px 4px 4px 4px;
    }

    .content {
        width: 100%;
        background-color: #fff;

        .drawerText {
            font-size: 1.125rem;
            font-weight: 700;
        }
    }

    :deep(.el-overlay .el-icon svg) {
        color: black;
    }

    .order ::v-deep(.el-select__prefix) {
        order: 2;
    }
}

/* 弹出框样式 */
::v-deep .el-overlay {
    .el-dialog__header {
        background-color: #116cf8;
        margin-right: 0;
    }

    .el-dialog__title {
        color: #fff;
    }

    .el-icon svg {
        color: #fff;
    }
}

:deep(.el-radio-group) {
    align-items: flex-start;
}

:deep(.el-pagination) {
    justify-content: center;
}

.el-row {
    width: 100%;
}
</style>
